package servlet;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.Java2D.Canvas;

import pasantias.Dominio.BoardBuilder;
import pasantias.Dominio.Dot;
import pasantias.Dominio.InmutableBoard;
import pasantias.Dominio.Rectangle;

public class RectangleServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public RectangleServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		int x = Integer.parseInt(request.getParameter("x"));
		int y = Integer.parseInt(request.getParameter("y"));
		int width = Integer.parseInt(request.getParameter("width"));
		int height = Integer.parseInt(request.getParameter("height"));

		Canvas canvas = new Canvas();
		BoardBuilder boardBuilder = new BoardBuilder(40, 40);
		boardBuilder.addFigure(new Rectangle(new Dot(x, y), width, height));
		InmutableBoard board = boardBuilder.build();
		board.draw(canvas);

		BufferedImage image = new BufferedImage(400, 400, BufferedImage.TYPE_INT_RGB);
		Graphics2D graphics2d = image.createGraphics();
		canvas.paintComponent(graphics2d);
		try {
			ImageIO.write(image, "jpg", response.getOutputStream());
		} catch (IOException ioe) {
			System.out.println("Clip write help: " + ioe.getMessage());
		}
		response.getOutputStream().close();

	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		doGet(request, response);
	}

}
